<?php

namespace app\component\easyWechat;


use EasyWeChat\Factory;
use Yii;
use yii\base\Component;

class miniProgram extends Component
{
    /**
     * @var string
     */
    public string $appid = '';

    /**
     * @var string
     */
    public string $secret = '';

    /**
     * @var array
     */
    private static $apps = [];

    /**
     * @return mixed
     */
    public static function getApps()
    {
        return self::$apps;
    }

    public function miniProgram()
    {

        if (isset(self::$apps[$this->appid])) {
            return self::$apps[$this->appid];
        }

        $config = [
            'app_id' => $this->appid,
            'secret' => $this->secret,
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => Yii::$app->basePath . '/wechat/' . date('Y-m-d') . '.log',
            ],
        ];
        $app = Factory::miniProgram($config);
//        $app->rebind('cache', new PsrCache());
        self::$apps[$this->appid] = $app;
        return $app;

    }

    /**
     * @param $jsCode
     * @return array
     * @throws \Exception
     */
    public function miniProgramAuth($jsCode)
    {

        $minApp = self::miniProgram();
        $resp = $minApp->auth->session($jsCode);
        $log['js_code'] = $jsCode;
        $log['resp'] = $resp;
        Yii::info(json_encode($log), 'analysis_min_app_auth');
        if (empty($resp['openid'])) {
            throw new \Exception('微信登录凭证校验失败');
        }

        $data['openid'] = $resp['openid'];
        $data['union_id'] = $resp['unionid'];

        return $data;

    }
}